import config from './config.js'
import pinia from '@/store/index.js'
import { useUserinfo } from '@/store/userInfo.js'


const request = ({url,data={},method='post',toast=true,needLogin=false}) => {
	const { token } = useUserinfo(pinia)
	return new Promise((resolve,reject) => {
		uni.request({
			// #ifdef MP-WEIXIN || MP-TOUTIAO
			url: config.proxy + url,
			// #endif
			// #ifdef H5
			url: config.baseUrl + url,
			// #endif
			method,
			dataType:'json',
			data: {
				// phonetype: store.getters.platform,
				token: needLogin?token:undefined,
				...data,
			}
		}).then(res => {
			if(res.statusCode === 200) {
				const data = res.data;
				if(data.code === 1) {
					resolve(data.data)
				}else if(data.code === -110) {
				}else {
					reject(data)
					if(!toast) return;
					uni.showToast({
						icon:'none',
						title: data.message || '服务端错误~'
					})
				}
			}else {
				reject(res)
				if(!toast) return;
				uni.showToast({
					icon:'none',
					title:'网络错误~'
				})
			}
		}).catch(err => {
			reject(err)
			if(!toast) return;
			uni.showToast({
				icon:'none',
				title: err.message || '未知错误~'
			})
		})
	})
}
const beforeRequest = ({url,data={},method='post',needLogin = false,toast = true}) => {
	const { requestList, hasLogin } = useUserinfo(pinia)
	if(hasLogin.value && needLogin) {
		// 需要已登录token，但是未登录或者登录接口未完成时如此处理，将请求挂起
		return new Promise((resolve,reject) => [
			requestList.value.push({
				request:request,
				data:{url,data,method,toast},
				resolve,
				reject
			})
		])
	}else {
		return request({url,data,method,toast,needLogin})
	}
}
export default beforeRequest